package com.dudy;

import java.util.LinkedList;
import java.util.List;

/**
 * @program: zhuguangDemo
 * @description: 有界阻塞队列
 * @author: dudy
 * @create: 2018-04-02 15:05
 **/
public class BlockQueueWN<T> {

    private List queue = new LinkedList();
    private final int limit;

    BlockQueueWN(int limit) {
        this.limit = limit;
    }

    /**
     * 入队
     * @param item
     */
    public synchronized void enqueuee(T item) {
        while (this.queue.size() == this.limit) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 唤醒出队线程，但因为synchronized，所以会优先执行下面的add方法，保证有元素，然后根据cpu调度来调用出队操作
        if (this.queue.isEmpty()) {
            notifyAll();
        }
        this.queue.add(item);
    }

    /**
     * 出队
     * @return
     */
    public synchronized T dequeue() {
        while (this.queue.size() == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (this.queue.size() == this.limit) {
            notifyAll();
        }
        return (T)this.queue.remove(0);
    }


}
